import { result } from 'lodash';
import { element } from 'protractor';
import { Component, Injector, ViewChild } from '@angular/core';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { MessageService } from '@abp/message/message.service';
import { Table } from 'primeng/components/table/table';
import { Paginator } from 'primeng/components/paginator/paginator';
import { InspectionStartServiceProxy, ProductionReportServiceProxy, InspectionFileCommonServiceServiceProxy, InspectionSeverityDescOutDto, InspectionStandardDescDto, CodeFormatDescServiceProxy, OperationHistoryServiceProxy, InspectionTypeDescDto, InspectionFileUploadDto } from '@shared/service-proxies/service-proxies';
import { finalize } from 'rxjs/operators';
import { AppComponentBase } from '@shared/common/app-component-base';
import { AppSessionService } from '@shared/common/session/app-session.service';
import { FileUploader, FileUploaderOptions } from 'ng2-file-upload';
import { FileUpload } from 'primeng/primeng';
import * as moment from 'moment';

@Component({
    selector: 'app-exception-management',
    templateUrl: './exception-management.component.html',
    styleUrls: ['./exception-management.component.less']
})
export class ExceptionManagementComponent extends AppComponentBase {
    @ViewChild('paginator') paginator: Paginator;
    @ViewChild('dataTable') dataTable: Table;

    @ViewChild('paginator') paginatorbg: Paginator;
    @ViewChild('dataTable') dataTablebg: Table;
    selectInfo: any[] = [];
    constructor(
        injector: Injector,
        private _messageService: MessageService,
        private _inspectionStartServiceProxy: InspectionStartServiceProxy,
        private _codeFormatDescServiceProxy: CodeFormatDescServiceProxy,
        private _operationHistoryServiceProxy: OperationHistoryServiceProxy,
        private _inspectionFileCommonServiceServiceProxy: InspectionFileCommonServiceServiceProxy,
        private _user: AppSessionService,
        private _productionReportServiceProxy: ProductionReportServiceProxy,
    ) {
        super(injector);
    }
    baogongSelect: any
    addVisible: boolean = false;//新增弹窗参数
    reportingVisible: boolean = false;//报工任务弹窗
    resumeVisible: boolean = false;//异常履历
    activeIndex: number = 0;//履历步骤条选中index
    sureVisible: boolean = false;//确认结果
    images = [];
    tasklist: any = [];//任务编号列表
    queryInfo = {
        taskCode: undefined,//任务编号
        inspectionTypeDescId: undefined,//一级异常id
        inspectionItemInfoId: undefined,//二级异常id
        inspectionSeverityDescId: undefined,//异常等级id
        submitterId: undefined,//提报人id
        handlerId: undefined,//处理人id
        userId: undefined,//查看人id 
    };//查询条件
    typeDescList: any[];//一级异常下拉
    itemInfoList: any[];//二级异常下拉
    severityDescList: InspectionSeverityDescOutDto[];//等级下拉
    userList: any[];//处理人 提报人下拉
    addInfoUi: any = {
        inspectionTypeDescId: undefined,//一级异常id
        inspectionItemInfoId: undefined,//二级异常id
        inspectionSeverityDescId: undefined,//异常等级id
        handlerId: undefined,//处理人id
        inspectionDetails: "",//异常描述
        codeFormatId: undefined,//编码规则id
        inspectionFileUploadDto: [],
        taskCode: undefined
    };//新增集合
    imagePath: any;
    imgURL: any;
    addInfo = new InspectionStandardDescDto();//新增集合
    savingAddDia: boolean = false;//禁止频繁保存操作
    savingsureDia: boolean = false;//禁止频繁保存操作
    formatDropList: any[];//编码规则 列表
    logList: any[];//异常履历 列表
    dialogType: string = '新增'
    oldList: any[];
    creationTime = undefined;
    sureSelect = [// 确认结果
        { label: '确认关闭', value: "4" },
        { label: '驳回', value: "3" }
    ];
    uploadedFiles: any[] = [];
    saveFlag = true;
    ngOnInit() {
        this.getTaskList()
        this.gettypeDescList()
        this.getSeverityDescList()
        this.getuserList()
        this.getFormatDropList()
    }
    //查询报工列表
    searchBgEv(taskCode, event?: LazyLoadEvent,) {
        if (this.primengSonTableHelper.shouldResetPaging(event)) {
            this.paginatorbg.changePage(0);
            return;
        }
        this._inspectionStartServiceProxy.getTaskReportList(
            taskCode,
            this.primengSonTableHelper.getSorting(this.dataTablebg),//undefined
            this.primengSonTableHelper.getMaxResultCount(this.paginatorbg, event),//10
            this.primengSonTableHelper.getSkipCount(this.paginatorbg, event) ? this.primengSonTableHelper.getSkipCount(this.paginatorbg, event) : 0//0
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.reportingVisible = true
                this.primengSonTableHelper.totalRecordsCount = result.totalCount;
                this.primengSonTableHelper.records = result.items;
                this.primengSonTableHelper.hideLoadingIndicator();
            });
    }
    // 报工增加
    addbaogongEv() {
        this.reportingVisible = false
        this.selectInfo.push(this.baogongSelect)
        this.addInfoUi.taskCode = this.baogongSelect
    }
    //上传图片删除操作
    myRemove(event) {
        let files = this.addInfoUi.inspectionFileUploadDto.filter((item) => {
            return item.fileName != event.file.name
        })
        this.addInfoUi.inspectionFileUploadDto = files
    }
    // 重置
    reset() {
        this.queryInfo = {
            taskCode: undefined,//任务编号
            inspectionTypeDescId: undefined,//一级异常id
            inspectionItemInfoId: undefined,//二级异常id
            inspectionSeverityDescId: undefined,//异常等级id
            submitterId: undefined,//提报人id
            handlerId: undefined,//处理人id
            userId: undefined,//查看人id 
        };//查询条件
    }
    //回显删除
    remoteFile(item) {
        let files = this.uploadedFiles.filter((ele) => {
            return ele.name != item.name
        })
        this.uploadedFiles = files
    }

    //异常列表
    getDescList(event?: LazyLoadEvent): void {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);
            return;
        }
        this._inspectionStartServiceProxy.getInspectionStandardDescList(
            this.queryInfo.taskCode,
            this.queryInfo.inspectionTypeDescId ? this.queryInfo.inspectionTypeDescId.id : undefined,
            this.queryInfo.inspectionItemInfoId ? this.queryInfo.inspectionItemInfoId.id : undefined,
            this.queryInfo.inspectionSeverityDescId ? this.queryInfo.inspectionSeverityDescId.id : undefined,
            this.queryInfo.submitterId ? this.queryInfo.submitterId.id : undefined,
            this.queryInfo.handlerId ? this.queryInfo.handlerId.id : undefined,
            this.queryInfo.userId ? this.queryInfo.userId.id : undefined,
            this.primengTableHelper.getSorting(this.dataTable),//undefined
            this.primengTableHelper.getMaxResultCount(this.paginator, event),//10
            this.primengTableHelper.getSkipCount(this.paginator, event)//0
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.primengTableHelper.totalRecordsCount = result.totalCount;
                this.primengTableHelper.records = result.items;
                this.primengTableHelper.hideLoadingIndicator();
                this.oldList = JSON.parse(JSON.stringify(result.items))
            });
    }
    //任务编号下拉列表
    getTaskList(): void {
        this._inspectionStartServiceProxy.getCodeTaskList(undefined)
            .pipe(finalize(() => { }))
            .subscribe(result => {
                let taskList: any = result
                taskList.forEach(element => {
                    let taskItem = {
                        value: element,
                        label: element
                    }
                    this.tasklist.push(taskItem)
                });
            });
    }
    //一级异常 下拉列表
    gettypeDescList(): void {
        this._inspectionStartServiceProxy.getInspectionTypeDescList(
            undefined
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.typeDescList = result
            });
    }

    //二级异常 下拉列表
    getItemInfoList(inspectionTypeDescId): void {
        this._inspectionStartServiceProxy.getInspectionItemInfoList(
            inspectionTypeDescId ? inspectionTypeDescId.id : undefined,
            undefined
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.itemInfoList = result
            });
    }
    //异常等级 下拉列表
    getSeverityDescList(): void {
        this._inspectionStartServiceProxy.getInspectionSeverityDescList(
            undefined
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.severityDescList = result
            });
    }
    //提报人/处理人 下拉列表
    getuserList(): void {
        this._inspectionStartServiceProxy.getUserList(
            this.queryInfo.inspectionItemInfoId,
            undefined
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.userList = result
            });
    }
    //编码规则 下拉列表
    getFormatDropList(): void {
        this._codeFormatDescServiceProxy.getCodeFormatDropList()
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.formatDropList = result
            });
    }
    // 上传图片
    myUploader() {
        this.addInfoUi.inspectionFileUploadDto = []
        for (const iterator of this.uploadedFiles) {
            if (iterator.lastModified) {
                let file = {
                    fileName: iterator.name,
                    data: iterator
                }
                this._inspectionFileCommonServiceServiceProxy.inspectionUploadFile(file, undefined).pipe(finalize(() => { }))
                    .subscribe(result => {
                        let obj = new InspectionFileUploadDto()
                        obj.fileName = result.fileName,
                            obj.id = result.id,
                            obj.fileUrl = result.fileUrl,
                            this.addInfoUi.inspectionFileUploadDto.push(obj)
                        if (iterator.name == this.uploadedFiles[this.uploadedFiles.length - 1].name) {
                            this.addService();
                        }
                    });
            } else {
                let obj = new InspectionFileUploadDto()
                obj.fileName = iterator.name,
                    obj.id = iterator.id,
                    obj.fileUrl = iterator.objectUrl,
                    this.addInfoUi.inspectionFileUploadDto.push(obj)
            }
        }


    }
    addService() {
        this.savingAddDia = true
        this.addInfo.inspectionTypeDescId = this.addInfoUi.inspectionTypeDescId.id
        this.addInfo.inspectionItemInfoId = this.addInfoUi.inspectionItemInfoId.id
        this.addInfo.inspectionSeverityDescId = this.addInfoUi.inspectionSeverityDescId.id
        this.addInfo.handlerId = this.addInfoUi.handlerId ? this.addInfoUi.handlerId.id : undefined
        this.addInfo.inspectionDetails = this.addInfoUi.inspectionDetails
        this.addInfo.userId = this._user.userId
        this.addInfo.taskCode = this.addInfoUi.taskCode ? this.addInfoUi.taskCode.jobNumber : undefined
        this.addInfo.taskCodeId = this.addInfoUi.taskCode ? this.addInfoUi.taskCode.id : '00000000-0000-0000-0000-000000000000'
        this.addInfo.inspectionFileUploadDto = this.addInfoUi.inspectionFileUploadDto
        if (this.addInfoUi.id) {
            this.addInfo.id = this.addInfoUi.id
        } else {
            this.addInfo.id = '00000000-0000-0000-0000-000000000000'
            this.addInfo.codeFormatId = '00000000-0000-0000-0000-000000000000'
        }
        if (this.saveFlag) {
            this.saveFlag = false;
            this._inspectionStartServiceProxy.createOrUpdateInspectionStandardDesc(
                this.addInfo
            )
                .pipe(finalize(() => { this.savingAddDia = false }))
                .subscribe(result => {
                    this.saveFlag = true;
                    if (result.code == 0) {
                        // this.userList = result
                        this.addVisible = false
                        this._messageService.success('添加成功');
                        this.getDescList()
                    } else {
                        this._messageService.error(result.message)
                    }
                });
        }
    }
    // 新增
    addStandardDesc(): void {
        this.myUploader()
    }
    // 异常履历
    getOperationLogList(id): void {
        this.resumeVisible = true
        this._operationHistoryServiceProxy.getOperationLogList(
            id
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.logList = result
            });
    }
    onUpload(event) {
        for (let file of event.files) {
            this.uploadedFiles.push(file);
        }
    }
    setInfo(item) {
        console.log(this.userList);
        
        //一级异常 回显
        this.addInfoUi.inspectionTypeDescId = this.typeDescList.filter((ele, index) => {
            return ele.id === item.inspectionTypeDescId
        })[0]
        //二级异常 回显
        this._inspectionStartServiceProxy.getInspectionItemInfoList(
            this.addInfoUi.inspectionTypeDescId.id,
            undefined
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.itemInfoList = result;
                this.addInfoUi.inspectionItemInfoId = this.itemInfoList.filter((ele, index) => {
                    return ele.id === item.inspectionItemInfoId
                })[0];
            });
        //异常等级 回显
        this.addInfoUi.inspectionSeverityDescId = this.severityDescList.filter((ele, index) => {
            return ele.id === item.inspectionSeverityDescId
        })[0]
        //处理人 回显
        if( this.userList){
            this.addInfoUi.handlerId = this.userList.filter((ele, index) => {
                return ele.id === item.handlerId
            })[0]
        }
       
        let imgArr = []
        item.inspectionFileUploadDto.forEach(element => {
            let obj = {
                name: element.fileName,
                size: element.size,
                objectURL: element.fileUrl,
                id: element.id,
            }
            imgArr.push(obj)
        });
        this.uploadedFiles = imgArr
        this.addInfoUi.inspectionFileUploadDto = item.inspectionFileUploadDto
    }
    fileChange(files) {
        if (files.length === 0) {
            return;
        }
        const reader = new FileReader();
        this.imagePath = files;
        reader.readAsDataURL(files[0]);
        reader.onload = () => {
            this.imgURL = reader.result;
        };
    }
    // 查看异常
    seeDetail(item): void {
        this.addVisible = true
        this.addInfoUi = null
        this.addInfoUi = JSON.parse(JSON.stringify(item))
        this.dialogType = '查看'
        this.setInfo(JSON.parse(JSON.stringify(item)))
        // this.searchBgEv(item.taskCode)
        this.selectInfo = []
        console.log(item);
        
        this._inspectionStartServiceProxy.getTaskReportList(
            item.taskCodeId==null?undefined:item.taskCodeId,
            this.primengSonTableHelper.getSorting(this.dataTablebg),//undefined
            10,
            0
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.selectInfo = result.items

            });
    }
    // 修改异常
    updateInfo(item): void {
        this.addInfoUi = null
        this.addInfoUi = JSON.parse(JSON.stringify(item))
        this.dialogType = '修改'
        this.addVisible = true
        this.setInfo(JSON.parse(JSON.stringify(item)))
        this.selectInfo = []
        this._inspectionStartServiceProxy.getTaskReportList(
            item.taskCodeId,
            this.primengSonTableHelper.getSorting(this.dataTablebg),//undefined
            10,
            0
        )
            .pipe(finalize(() => { }))
            .subscribe(result => {
                this.selectInfo = result.items
            });
    }
    onHideSureVisible() {
        this.creationTime = undefined;
        this.images = [];
    }
    // 确认结果
    sureInfo(item): void {
        this.addInfoUi = item
        this.addInfo = this.oldList.filter((ele, index) => {
            return ele.id === item.id
        })[0];
        this.creationTime = moment(this.addInfo.creationTime).format('YYYY-MM-DD HH:mm:ss');
        this.sureVisible = true
        this.setInfo(JSON.parse(JSON.stringify(item)))
        //图片处理
        for (const item of this.addInfo.inspectionFileUploadDto) {
            let obj = {
                source: item.fileUrl,
                thumbnail: item.fileUrl,
                title: item.fileName,
            };
            this.images.push(obj);
        }

    }
    // 确认结果  提交
    submitEv(): void {
        this.savingsureDia = true
        this.addInfo.confirmSuggest = this.addInfoUi.confirmSuggest;
        this.addInfo.costTime = this.addInfoUi.costTime
        this.addInfo.state = this.addInfoUi.state.value
        this.addInfo.confirmTime = this.addInfoUi.confirmTime
        if (this.saveFlag) {
            this.saveFlag = false;
            this._inspectionStartServiceProxy.createOrUpdateInspectionStandardDesc(
                this.addInfo
            )
                .pipe(finalize(() => { this.savingsureDia = false }))
                .subscribe(result => {
                    this.saveFlag = true;
                    if (result.code == 0) {
                        this.sureVisible = false;
                        this._messageService.success('确认成功');
                    } else {
                        this._messageService.error(result.message)
                    }
                });
        }
    }

    //新增弹窗隐藏
    displayclose(): void {
        this.addInfoUi = {
            inspectionTypeDescId: undefined,//一级异常id
            inspectionItemInfoId: undefined,//二级异常id
            inspectionSeverityDescId: undefined,//异常等级id
            handlerId: undefined,//处理人id
            inspectionDetails: "",//异常描述
            codeFormatId: undefined,//编码规则id
            inspectionFileUploadDto: [],
            taskCode: undefined
        };//新增集合
        this.uploadedFiles = []
        this.selectInfo = []
    }

    // 删除事件
    deleteEv(id): void {
        this._messageService.confirm(
            '是否删除这条数据？',
            (isConfirmed) => {
                if (isConfirmed) {
                    if (this.saveFlag) {
                        this.saveFlag = false;
                        this._inspectionStartServiceProxy.deleteInspectionStandardDesc(
                            id
                        )
                            .pipe(finalize(() => { }))
                            .subscribe(result => {
                                this.saveFlag = true;
                                if (result.code == 0) {
                                    this.getDescList()
                                    this._messageService.success('删除成功');
                                } else {
                                    this._messageService.error(result.message)
                                }


                            });
                    }

                }
            }
        );
    }

}
